import Taro from '@tarojs/taro';
import requestWithJsonp from '@/utils/jsonp';

//腾讯逆地址解析webApi
async function regeo(coordinate) {
  let statusCode, data;

  if (Taro.$isH5) {
    await requestWithJsonp(
      `https://apis.map.qq.com/ws/geocoder/v1/?location=${coordinate.latitude},${coordinate.longitude}&key=${LOCATION_APIKEY}&output=jsonp`,
    )
      .then((allData) => {
        data = allData;
      })
      .catch(function (error) {
        throw new Error(`获取地址失败${error}`);
      });
  } else {
    const result = await Taro.request({
      url: `https://apis.map.qq.com/ws/geocoder/v1/?location=${coordinate.latitude},${coordinate.longitude}&key=${LOCATION_APIKEY}`,
      mode: 'no-cors',
      cache: 'no-cache',
    });
    statusCode = result.statusCode;
    data = result.data;
    if (statusCode !== 200) {
      throw new Error(`获取地址失败${statusCode}`);
    }
  }

  if (data?.status !== 0) {
    throw new Error(`获取地址失败${data?.status}`);
  }

  const adcode = data?.result?.ad_info?.adcode;
  const address = data?.result?.address;

  const { province, city, district, street: township } = data?.result?.address_component ?? {};

  return {
    adcode,
    address,

    province,
    city: !city?.length ? undefined : city,
    district,
    township,
  };
}

export { regeo };
